package com.jml.transaction;

import com.jml.entity.OrderEntity;
import com.jml.manage.OrderManage;
import com.jml.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = "spring_boot_producer_group")
public class SyncProducerListener implements RocketMQLocalTransactionListener {
    private AtomicInteger trnner = new AtomicInteger(0);
    @Autowired
    private OrderManage orderManage;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            String orderId = new String((byte[]) message.getPayload());
            if (StringUtils.isEmpty(orderId)) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            orderManage.insertOrder(orderId);
            log.info("【本地业务执行完毕】 msg:{}, Object:{}", message, o);
//            int i = 1 / 0;
            // 本地事务执行成功
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.info(">>e:{}<<", e);
            // 本地事务执行异常
            log.error("【执行本地业务异常】 exception message:{}", e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }


    /**
     * RocketMQ 会每隔1分钟间隔调用该：checkLocalTransaction检测本地是否有执行过
     * BrokderC  transactionCheckInterval   60 * 1000;
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("【执行检查任务】");
        String orderId = new String((byte[]) message.getPayload());
        OrderEntity orderEntity = orderMapper.findOrderId(orderId);
        // 如果该不存在对象情况下
        if (orderEntity == null) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        // 如果该对象存在的情况下，则提交该事务 返回提交状态给rocketmq
        return RocketMQLocalTransactionState.COMMIT;
    }
}